package com.uzai.console.web.pdd;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.annotation.SystemLogType;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.component.excel.listener.ExcelListener;
import com.uzai.console.component.excel.template.PddPunishOrderExcelDemo;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.pdd.pddorder.*;
import com.uzai.console.dto.pdd.pddtoken.PddTokenQuery;
import com.uzai.console.dto.user.UserQuery;
import com.uzai.console.entity.PddToken;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.mapper.PddTokenMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.device.DeviceTypeService;
import com.uzai.console.service.pdd.PddPunishOrderService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoService;
import com.uzai.console.service.pdd.PddOrderService;
import com.uzai.console.service.order.OrderReStatusService;
import com.uzai.console.service.order.OrderSourceService;
import com.uzai.console.service.order.OrderStatusService;
import com.uzai.console.vo.base.SelectKeyVo;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.user.UserInfoVo;
import com.uzai.console.vo.pdd.pddorder.PddOrderInfoVo;
import com.uzai.console.vo.pdd.pddorder.PddOrderReportVo;
import com.uzai.console.vo.order.OrderReStatusVo;
import com.uzai.console.vo.order.OrderSourceVo;
import com.uzai.console.vo.order.OrderStatusVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 产品
 * @author liuqi
 * @date 2021年08月16日 15:11
 */
@Api(value = "拼多多订单",tags = "拼多多|拼多多订单")
@ApiSort(11)
@RestController
public class PddOrderController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(PddOrderController.class);

    @Autowired
    private PddOrderService pddOrderService;
    @Autowired
    private OrderStatusService orderStatusService;
    @Autowired
    private OrderReStatusService orderReStatusService;
    @Autowired
    private OrderSourceService orderSourceService;
    @Autowired
    private PddTokenMapper pddTokenMapper;
    @Autowired
    private DeviceWechatInfoService deviceWechatInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeviceTypeService deviceTypeService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private PddPunishOrderService pddPunishOrderService;

    @ApiOperation(value = "查询拼多多订单列表", notes = "查询拼多多订单列表", response = PddOrderInfoVo.class)
    @ApiOperationSupport(order = 1)
    @PostMapping("/pddOrder/findPddOrderList")
    public Object findPddOrderList(@RequestBody PddOrderQuery pddOrderQuery){
        return pddOrderService.findPddOrderList(pddOrderQuery);
    }

    @ApiOperation(value = "查询拼多多订单详情", notes = "查询拼多多订单详情", response = PddOrderInfoVo.class)
    @ApiOperationSupport(order = 2)
    @PostMapping("/pddOrder/findPddOrderInfo")
    public Object findPddOrderInfo(@RequestBody PddOrderIdDto pddOrderIdDto){
        return pddOrderService.findPddOrderInfo(pddOrderIdDto);
    }

    @ApiOperation(value = "查询拼多多订单统计信息(总收入、买家总金额、总利润）", notes = "查询拼多多订单统计信息(总收入、买家总金额、总利润）", response = PddOrderReportVo.class)
    @ApiOperationSupport(order = 3)
    @PostMapping("/pddOrder/findPddOrderReport")
    public Object findPddOrderReport(@RequestBody PddOrderQuery pddOrderQuery){
        return pddOrderService.findPddOrderRepot(pddOrderQuery);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "订单删除", notes = "订单删除")
    @ApiOperationSupport(order = 4)
    @PostMapping("/pddOrder/delPddOrder")
    public Object delPddOrder(@RequestBody PddOrderDelDto pddOrderDelDto){
        return pddOrderService.delPddOrder(pddOrderDelDto);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "确认收货", notes = "确认收货")
    @ApiOperationSupport(order = 5)
    @PostMapping("/pddOrder/confirmReceive")
    public Object confirmReceive(@RequestBody PddOrderIdDto pddOrderIdDto){
        return pddOrderService.confirmReceive(pddOrderIdDto);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "手动维权", notes = "手动维权")
    @ApiOperationSupport(order = 6)
    @PostMapping("/pddOrder/confirmRefund")
    public Object confirmRefund(@RequestBody PddOrderIdDto pddOrderIdDto){
        return pddOrderService.confirmRefund(pddOrderIdDto);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "订单冻结", notes = "订单冻结")
    @ApiOperationSupport(order = 7)
    @PostMapping("/pddOrder/confirmFrozen")
    public Object confirmFrozen(@RequestBody PddOrderIdDto pddOrderIdDto){
        return pddOrderService.confirmFrozen(pddOrderIdDto);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "订单解冻", notes = "订单解冻")
    @ApiOperationSupport(order = 8)
    @PostMapping("/pddOrder/confirmThaw")
    public Object confirmThaw(@RequestBody PddOrderIdDto pddOrderIdDto){
        return pddOrderService.confirmThaw(pddOrderIdDto);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "解绑用户", notes = "解绑用户")
    @ApiOperationSupport(order = 9)
    @PostMapping("/pddOrder/unbindUser")
    public Object unBindUser(@RequestBody PddOrderUnbindUserDto pddOrderUnbindUserDto){
        return pddOrderService.unbindUser(pddOrderUnbindUserDto);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "绑定用户", notes = "绑定用户")
    @ApiOperationSupport(order = 10)
    @PostMapping("/pddOrder/bindUser")
    public Object bindUser(@RequestBody PddOrderBindUserDto pddOrderBindUserDto){
        return pddOrderService.bindUser(pddOrderBindUserDto);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改解冻时间", notes = "修改解冻时间")
    @ApiOperationSupport(order = 11)
    @PostMapping("/pddOrder/updateThawTime")
    public Object updateThawTime(@RequestBody PddOrderThawTimeDto pddOrderThawTimeDto){
        return pddOrderService.updateThawTime(pddOrderThawTimeDto);
    }

    @ApiOperation(value = "查询联盟账号接口", notes = "查询联盟账号接口", response = SelectKeyVo.class)
    @ApiOperationSupport(order = 12)
    @PostMapping("/pddOrder/findAlimmList")
    public Object findAlimmList(){
        List<SelectKeyVo> selectIdVoList = new ArrayList<>();
        PddTokenQuery pddTokenQuery = new PddTokenQuery();
        pddTokenQuery.setMerId(getLoginInfo().getMerId());
        List<PddToken> pddTokenList = pddTokenMapper.findByList(pddTokenQuery);
        if(pddTokenList != null){
            int now = DateUtil.getNowTime();
            for (PddToken pddToken : pddTokenList){
                SelectKeyVo selectKeyVo = new SelectKeyVo();
                selectKeyVo.setKey(String.valueOf(pddToken.getId()));
                selectKeyVo.setValue(pddToken.getUserId());
                int expiredTime = Tools.getInteger(pddToken.getExpiresin()).intValue() + Tools.getInteger(pddToken.getAuthTime()).intValue();
                if(expiredTime <= now){
                    selectKeyVo.setExptimeFlag(1); //已到期
                }else{
                    selectKeyVo.setExptimeFlag(0); //未到期
                }
                selectIdVoList.add(selectKeyVo);
            }
        }
        return selectIdVoList;
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPLOAD)
    @ApiOperation(value = "手动下载拼多多订单", notes = "手动下载拼多多订单")
    @ApiOperationSupport(order = 13)
    @PostMapping("/pddOrder/downloadOrder")
    public Object downloadOrder(@RequestBody PddOrderDownLoadDto pddOrderDownLoadDto){
        pddOrderService.downloadOrder(pddOrderDownLoadDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPLOAD)
    @ApiOperation(value = "订单刷新", notes = "订单刷新")
    @ApiOperationSupport(order = 14)
    @PostMapping("/pddOrder/refreshOrder")
    public Object refreshOrder(@RequestBody PddOrderIdDto pddOrderIdDto){
        pddOrderService.refreshOrder(pddOrderIdDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPLOAD)
    @ApiOperation(value = "批量订单刷新", notes = "批量订单刷新")
    @ApiOperationSupport(order = 14)
    @PostMapping("/pddOrder/refreshOrder/batch")
    public Object batchRefreshOrder(@RequestBody PddOrderChildOrderNoDto pddOrderChildOrderNoDto){
        pddOrderService.batchRefreshOrder(pddOrderChildOrderNoDto);
        return true;
    }


    @ApiOperation(value = "查询所有未绑定用户订单", notes = "查询所有未绑定用户订单")
    @ApiOperationSupport(order = 15)
    @PostMapping("/pddOrder/findUnbindUserList")
    public Object findUnbindUserList(@RequestBody PddOrderUnbindDtoQuery pddOrderUnbindDtoQuery){
        return pddOrderService.findUnbindUserList(pddOrderUnbindDtoQuery);
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除所有未绑定用户订单", notes = "删除所有未绑定用户订单")
    @ApiOperationSupport(order = 16)
    @PostMapping("/pddOrder/deleteUnbindUserList")
    public Object deleteUnbindUserList(@RequestBody PddOrderDeleteUnbindDto pddOrderDeleteUnbindDto){
        pddOrderDeleteUnbindDto.setDelStatus(1); //1表示已删除
        pddOrderDeleteUnbindDto.setUpdateTime(DateUtil.getNowTime());
        return pddOrderService.deleteUnbindUserList(pddOrderDeleteUnbindDto);
    }

    @ApiOperation(value = "查询拼多多订单状态列表", notes = "查询拼多多订单状态列表", response = OrderStatusVo.class)
    @ApiOperationSupport(order = 17)
    @PostMapping("/pddOrder/getOrderStatusList")
    public Object getOrderStatusList() {
        return orderStatusService.findPddOrderStatusList();
    }

    @ApiOperation(value = "查询拼多多订单返利状态列表", notes = "查询拼多多订单返利状态列表", response = OrderReStatusVo.class)
    @ApiOperationSupport(order = 18)
    @PostMapping("/pddOrder/getOrderReStatusList")
    public Object getOrderReStatusList() {
        return orderReStatusService.findOrderReStatusList();
    }

    @ApiOperation(value = "查询拼多多订单来源列表", notes = "查询拼多多订单订单来源列表", response = OrderSourceVo.class)
    @ApiOperationSupport(order = 19)
    @PostMapping("/pddOrder/getOrderSourceList")
    public Object getOrderSourceList() {
        return orderSourceService.findOrderSourceList();
    }

    @ApiOperation(value = "查询机器人下拉列表", notes = "查询机器人下拉列表", response = DeviceInfoVo.class)
    @ApiOperationSupport(order = 20)
    @PostMapping("/pddOrder/findDeviceWechatInfoSelectList")
    public Object findDeciceWechatInfoSelectList() {
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setMerId(getLoginInfo().getMerId());
        return deviceService.findDeviceList(deviceQuery);
    }

    @ApiOperation(value = "查询所有未绑定用户订单统计信息(总收入、买家总金额、总利润、未绑定用户利润、未收货返利金额）", notes = "查询所有未绑定用户订单统计信息(总收入、买家总金额、总利润、未绑定用户利润、未收货返利金额）", response = PddOrderReportVo.class)
    @ApiOperationSupport(order = 21)
    @PostMapping("/pddOrder/findUnbindUserReport")
    public Object findUnbindUserReport(@RequestBody PddOrderUnbindDtoQuery pddOrderUnbindDtoQuery){
        return pddOrderService.findUnbindUserReport(pddOrderUnbindDtoQuery);
    }

    @ApiOperation(value = "分页查询会员信息列表", notes = "分页查询会员信息列表", response = UserInfoVo.class)
    @ApiOperationSupport(order = 22)
    @PostMapping("/pddOrder/findUserPage")
    public Object findUserPage(@RequestBody UserQuery userQuery) {
        return userService.findUserPage(userQuery);
    }

    @ApiOperation(value = "查询设备类型下拉列表", notes = "查询设备类型下拉列表", response = SelectKeyVo.class)
    @ApiOperationSupport(order = 23)
    @PostMapping("/pddOrder/findDeiviceTypeListSelect")
    public Object findDeiviceTypeListSelect() {
        return deviceTypeService.findDeviceTypeListSelect();
    }

    @ApiOperation(value = "上传处罚订单文件", notes = "上传处罚订单文件")
    @ApiOperationSupport(order = 24)
    @PostMapping("/pddOrder/uploadPddPunishOrderFile")
    public Object uploadPddPunishOrderFile(MultipartFile file){

        //文件上传不能拦截参数赋值
        if(file == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "文件不存在");
        }

        try {

            ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.CSV;

            if(file.getOriginalFilename().endsWith(".csv")){
                excelTypeEnum = ExcelTypeEnum.CSV;
            }else if(file.getOriginalFilename().endsWith(".xls")){
                excelTypeEnum = ExcelTypeEnum.XLS;
            }else{
                excelTypeEnum = ExcelTypeEnum.XLSX;
            }

            EasyExcel.read(file.getInputStream(), PddPunishOrderExcelDemo.class, new ExcelListener(p->{
                //保存逻辑（可封装一个普通的sevice）p-为我们执行函数时传入的list
                pddPunishOrderService.uploadPddPunishOrderFile(p, getLoginInfo().getMerId());
            })).excelType(excelTypeEnum).sheet().doRead();
        } catch (IOException e) {
            logger.error("上传处罚订单失败:error={}", e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上传失败");
        }
        return true;
    }

    @SystemLogType(model = SystemModelEnum.PddOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "追回返利", notes = "追回返利")
    @ApiOperationSupport(order = 25)
    @PostMapping("/pddOrder/rebateRefound")
    public Object rebateRefound(@RequestBody PddOrderIdDto pddOrderIdDto){
        return pddOrderService.rebateRefound(pddOrderIdDto);
    }
}
